/**
 * 
 */
package com.tianqi.rms.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.tianqi.rms.model.WeixinUser;
import com.tianqi.rms.model.business.Bespeak;
import com.tianqi.rms.model.business.Pics;
import com.tianqi.rms.model.business.Services;
import com.tianqi.rms.model.business.Shop;
import com.tianqi.rms.model.business.Vip;
import com.tianqi.rms.model.business.Worker;
import com.tianqi.rms.sendFactory.SendFactory;
import com.tianqi.rms.sendFactory.SmsSender;
import com.tianqi.rms.util.OauthUtils;
import com.tianqi.rms.util.SmsTypeEnum;

/**
 *
 *                #####################################################
 *                #                                                   #
 *                #                       _oo0oo_                     #
 *                #                      o8888888o                    #
 *                #                      88" . "88                    #
 *                #                      (| -_- |)                    #
 *                #                      0\  =  /0                    #
 *                #                    ___/`---'\___                  #
 *                #                  .' \\|     |# '.                 #
 *                #                 / \\|||  :  |||# \                #
 *                #                / _||||| -:- |||||- \              #
 *                #               |   | \\\  -  #/ |   |              #
 *                #               | \_|  ''\---/''  |_/ |             #
 *                #               \  .-\__  '-'  ___/-. /             #
 *                #             ___'. .'  /--.--\  `. .'___           #
 *                #          ."" '<  `.___\_<|>_/___.' >' "".         #
 *                #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 *                #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 *                #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 *                #                       `=---='                     #
 *                #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 *                #                                                   #
 *                #               佛祖保佑         永无BUG              #
 *                #                        						      #
 *                #####################################################
 *								yanglong : Dec 12, 2018 10:36:06 PM 尊上
 *									预约信息
 */
public class BespeakController extends Controller {

	String base_url = PropKit.use("a_little_config.txt").get("baseUrl")+"bespeak/";
	int shop_id = Integer.parseInt(PropKit.use("a_little_config.txt").get("shop_id"));

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 12, 2018 10:38:07 PM   
	 * @version
	 *******************************************
	 */
	public void oauth() {
		int id = getParaToInt("id");
		String redirect_uri = base_url+"toBespeak?id="+id;
		String return_url = OauthUtils.publicOauth(redirect_uri);
		redirect(return_url);
	}

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 12, 2018 10:39:15 PM   
	 * @version
	 *******************************************
	 */
	public void toBespeak() {
		String code = getPara("code");
		int id = getParaToInt("id");
		if(code != null){
			ApiConfig ac = ApiConfigKit.getApiConfig();
			ApiConfigKit.putApiConfig(ac);
			ApiConfigKit.setThreadLocalAppId(ac.getAppId());
			String appId = ac.getAppId();
			String secret = ac.getAppSecret();
			SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
			Integer errorCode=snsAccessToken.getErrorCode();
			if(errorCode!=null) {
				redirect("/bespeak/oauth?id="+id);
				return;
			}
			String openId = snsAccessToken.getOpenid();
			try {
				WeixinUser wxUser = WeixinUser.dao.getUserByOpenId(openId);
				//用户直接进没有注册
				if(wxUser==null) {
					redirect("/enroll/oauth");
					return;
				}
				Worker work =Worker.dao.findById(id);
				work.setPic(Pics.dao.findById(work.getPhoto()));
				Vip vip = Vip.dao.getVipByUserTel(wxUser.getTel(), shop_id);
				List<Services> serviceList = Services.dao.getServices(shop_id);
				setAttr("serviceList", serviceList);
				setAttr("work", work);
				setAttr("vip", vip);
				setAttr("pagetype", "bespeak");
				render("bespeak.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 13, 2018 1:12:23 AM   
	 * @version
	 * @throws ParseException 
	 *******************************************
	 */
	public void save() throws ParseException {
		Map<String, Object> map=new HashMap<String, Object>();
		int id = getParaToInt("id");
		int vipid = getParaToInt("vipid");
		int selectservice = getParaToInt("selectservice");
		String day = getPara("day");
		String time =getPara("time")+":00";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataTime = day+" "+time;
		//预约时间
		Date saveDate=sdf.parse(dataTime);
		if(saveDate.before(new Date())) {
			map.put("code", -1);
			renderJson(map);
			return;
		}
		List<Bespeak> beks = Bespeak.dao.getBespeak(shop_id,day);
		if(beks.size()>0) {
			//今日已经预约
			map.put("code", -2);
			renderJson(map);
			return;
		}
		Bespeak bek = new Bespeak();
		bek.setCreateTime(new Date());
		bek.setDate(saveDate);
		bek.setProject(selectservice);
		bek.setShopId(shop_id);
		bek.setVipId(vipid);
		bek.setWorkId(id);
		if(bek.save()) {
			//预约成功
			map.put("code", 1);
			Shop shop = Shop.dao.findById(shop_id);
			Worker worker = Worker.dao.findById(bek.getWorkId());
			SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");
			String params =shop.getTitle()+"|"+worker.getName()+"|"+df.format(bek.getDate());
			String tel = Vip.dao.findById(vipid).getTel();
		
			SmsSender UserBookingsender =SendFactory.prouctSend(SmsTypeEnum.USERBOOKING);
			SmsSender acceptSender =SendFactory.prouctSend(SmsTypeEnum.ACCEPT);
			//用户预约成功发送短信
			UserBookingsender.Send(tel,params);
			//给美发师发送短信
			String paramsToworker =Vip.dao.findById(vipid).getName()+"("+tel+")|"
									+df.format(bek.getDate())+
									"|("+Services.dao.findById(selectservice).getTitle()+")";
			acceptSender.Send(worker.getTel(), paramsToworker);
			renderJson(map);
			return;
		}
	}


	public void oauthList() {
		String redirect_uri = base_url+"bespeakList";
		String return_url = OauthUtils.publicOauth(redirect_uri);
		redirect(return_url);
	}
	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 13, 2018 5:30:29 PM   
	 * @version
	 *******************************************
	 */
	public void bespeakList() {
		String code = getPara("code");
		if(code != null){
			ApiConfig ac = ApiConfigKit.getApiConfig();
			ApiConfigKit.putApiConfig(ac);
			ApiConfigKit.setThreadLocalAppId(ac.getAppId());
			String appId = ac.getAppId();
			String secret = ac.getAppSecret();
			SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
			Integer errorCode=snsAccessToken.getErrorCode();
			if(errorCode!=null) {
				redirect("/bespeak/oauthList");
				return;
			}
			String openId = snsAccessToken.getOpenid();
			try {
				WeixinUser wxUser = WeixinUser.dao.getUserByOpenId(openId);
				//用户直接进没有注册
				if(wxUser==null) {
					redirect("/enroll/oauth");
					return;
				}
				Vip vip = Vip.dao.getVipByUserTel(wxUser.getTel(), shop_id);
				//type  1:按周查询  2:按月查询 3：当天
				List<Bespeak> beks = Bespeak.dao.getBespeak(vip.getId(),shop_id,null,1);
				for (Bespeak bespeak : beks) {
					Worker worker = Worker.dao.findById(bespeak.getWorkId());
					worker.setPic(Pics.dao.findById(worker.getPhoto()));
					bespeak.setWorker(worker);
					bespeak.setServices(Services.dao.findById(bespeak.getProject()));
				}
				//获取当天数据
				List<Bespeak> beksDay = Bespeak.dao.getBespeak(vip.getId(),shop_id,null,3);
				for (Bespeak bespeak : beksDay) {
					Worker worker = Worker.dao.findById(bespeak.getWorkId());
					worker.setPic(Pics.dao.findById(worker.getPhoto()));
					bespeak.setWorker(worker);
					bespeak.setServices(Services.dao.findById(bespeak.getProject()));
				}
				setAttr("vip", vip);
				setAttr("pagetype", "bespeak");
				setAttr("nowDate", new Date());
				setAttr("beksDay", beksDay);
				setAttr("beks", beks);
				render("bespeak_week.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	/**
	*******************************************
	* 项目名称:weixin_meifa   
	* 方法名称:
	* 创建人：yanglong
	* 创建时间：Dec 14, 2018 6:50:25 PM   
	* @version
	*******************************************
	*/
	public void getserviceListAjax() {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<Services> serviceList = Services.dao.getServices(shop_id);
		for (Services services : serviceList) {
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("id", services.getId());
			map.put("value", services.getTitle());
			mapList.add(map);
		}
		renderJson(mapList);
	}
	
	/**
	*******************************************
	* 项目名称:weixin_meifa   
	* 方法名称:取消预约
	* 创建人：yanglong
	* 创建时间：Dec 14, 2018 7:41:16 PM   
	* @version
	*******************************************
	 */
	public void cancelService() {
		int id = getParaToInt("id");
		Bespeak bes = Bespeak.dao.findById(id);
		if(bes!=null) {
			bes.setState(-1);
			if(bes.update()) {
				Worker worker = Worker.dao.findById(bes.getWorkId());
				SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");
				String tel = Vip.dao.findById(bes.getVipId()).getTel();
				//尊敬的用户:您已经成功取消了{1}的预约。欢迎您再次使用!
				SmsSender Usercancelsender =SendFactory.prouctSend(SmsTypeEnum.USERCANCEL);
				Usercancelsender.Send(tel, df.format(bes.getDate()));
				//「取消预约」亲爱的美发师:{1}：会员{2}取消了在{4}的{5}服务。	
				SmsSender CancelSender=SendFactory.prouctSend(SmsTypeEnum.CANCEL);
				String params=worker.getName()+
						"|"+ Vip.dao.findById(bes.getVipId()).getName()+"("+tel+")"+
						"|"+df.format(bes.getDate())+"|("+Services.dao.findById(bes.getProject()).getTitle()+")";
				CancelSender.Send(worker.getTel(), params);
				
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("code", 1);
				renderJson(map);
			}
		}
	}

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 13, 2018 12:51:01 AM   
	 * @version
	 *******************************************
	 */
	public void go() {
		Worker work =Worker.dao.findById(37);
		work.setPic(Pics.dao.findById(work.getPhoto()));
		Vip vip = Vip.dao.getVipByUserTel("18919986087", shop_id);
		setAttr("work", work);
		setAttr("vip", vip);
		render("bespeak.jsp");
	}
	
	public void MonthList() {
		int vipId = getParaToInt("vipId");
		Vip vip = Vip.dao.findById(vipId);
		//type  1:按周查询  2:按月查询 3：当天
		List<Bespeak> beks = Bespeak.dao.getBespeak(vip.getId(),shop_id,null,2);
		for (Bespeak bespeak : beks) {
			Worker worker = Worker.dao.findById(bespeak.getWorkId());
			worker.setPic(Pics.dao.findById(worker.getPhoto()));
			bespeak.setWorker(worker);
			bespeak.setServices(Services.dao.findById(bespeak.getProject()));
		}
		setAttr("pagetype", "bespeak");
		setAttr("nowDate", new Date());
		setAttr("beks", beks);
		render("bespeak_month.jsp");
	}
}
